package main

import (
	"context"
	"log"
	"net/http"
	"os"
	"os/signal"
	"time"

	"learning-go-micro/handlers"
)

func main() {
	l := log.New(os.Stdout, "product-api", log.LstdFlags)
	hh := handlers.NewHello(l)
	gh := handlers.NewGoodbye(l)
	sm := http.NewServeMux()
	sm.Handle("/", hh)
	sm.Handle("/goodbye", gh)
	sm.Handle("/products", handlers.NewProducts(l))
	s := &http.Server{
		Addr:         ":9000",
		Handler:      sm,
		IdleTimeout:  120 * time.Second,
		ReadTimeout:  1 * time.Second,
		WriteTimeout: 1 * time.Second,
	}

	go func() {
		err := s.ListenAndServe()
		CheckErr(err, l)
	}()

	sigChan := make(chan os.Signal)
	signal.Notify(sigChan, os.Interrupt)
	signal.Notify(sigChan, os.Kill)
	sig := <-sigChan
	l.Println("Recieved terminate,graceful shutdown", sig)
	deadline := time.Now().Add(30 * time.Second)
	tc, cancelCtx := context.WithDeadline(context.Background(), deadline)
	defer cancelCtx()
	s.Shutdown(tc)
}
func CheckErr(err error, l *log.Logger) {
	if err != nil {
		l.Fatal(err)
	}
}
